<template>
  <div class="product">
    <nav-bar />
    <div class="main">
      <van-skeleton :row="16" avatar title :loading="skeletonLoading">
        <header-user
          v-if="product"
          :user="product.user"
          :time="product?.updateTime"
        />
        <div class="detail">
          <div class="price">
            <div class="new">
              ¥ <strong>{{ product?.newPrice }}</strong>
            </div>
            <div class="old">¥{{ product?.oldPrice }}</div>
          </div>
          <div class="desc">
            {{ product?.description }}
          </div>
          <div class="imgs">
            <div v-for="(img, index) in product?.imgList" :key="img">
              <van-image
                :src="img"
                lazy-load
                radius="10"
                width="100%"
                fit="cover"
                @click="onClickImg(index)"
              />
            </div>
          </div>
        </div>
      </van-skeleton>
    </div>
    <div class="bottom">
      <van-action-bar>
        <van-action-bar-icon icon="chat-o" text="客服" />
        <van-action-bar-icon
          v-if="isCollection"
          icon="star"
          text="已收藏"
          color="#88c4fc"
          @click="onRemoveCollection"
        />
        <van-action-bar-icon
          v-else
          icon="star-o"
          text="收藏"
          @click="onAddCollection"
        />
        <template v-if="currentUser?.id === product?.userId">
          <van-action-bar-button
            color="#64b4fc"
            type="danger"
            text="删除"
            @click="onDelete"
          />
          <van-action-bar-button
            color="#1e8dfc"
            type="danger"
            text="修改"
            @click="onEdit"
          />
        </template>
        <van-action-bar-button
          v-else
          color="#1e8dfc"
          type="danger"
          text="立即购买"
          @click="isShowActionSheet = true"
        />
      </van-action-bar>
    </div>
    <van-action-sheet
      v-model:show="isShowActionSheet"
      :actions="actions"
      @select="onSelect"
    />
  </div>
</template>

<script setup lang="ts">
import { deleteProductById, getProduct } from '../../../service/product'
import { productDetail } from '../../../service/product/types'
import NavBar from '../../../components/nav-bar.vue'
import HeaderUser from '../../../components/header-user.vue'
import { useUserStore } from '../../../store/user'
import {
  addCollection,
  checkIsCollection,
  removeCollectionByProductId
} from '../../../service/collection'
import { ActionSheetAction, Dialog, ImagePreview, Notify, Toast } from 'vant'
import { storeToRefs } from 'pinia'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()
const { user: currentUser } = storeToRefs(userStore)
const product = ref<productDetail.Product>()
const isCollection = ref<boolean>(false)
const isShowActionSheet = ref<boolean>(false)
const skeletonLoading = ref<boolean>(true)
const actions = ref<ActionSheetAction[]>([])

const onSelect = (action: ActionSheetAction) => {
  copyToClipboard(action.className as string)
    .then(() => {
      Notify({
        type: 'success',
        message: '复制成功'
      })
      isShowActionSheet.value = false
    })
    .catch(() => {
      Notify({
        type: 'warning',
        message: '复制失败,请手动复制'
      })
    })
}
const copyToClipboard = (textToCopy: string) => {
  // navigator clipboard api needs a secure context (https)
  if (navigator.clipboard && window.isSecureContext) {
    // navigator clipboard api method'
    return navigator.clipboard.writeText(textToCopy)
  } else {
    // text area method
    let textArea = document.createElement('textarea')
    textArea.value = textToCopy
    // make the textarea out of viewport
    textArea.style.position = 'fixed'
    textArea.style.left = '-999999px'
    textArea.style.top = '-999999px'
    document.body.appendChild(textArea)
    textArea.focus()
    textArea.select()
    return new Promise<void>((res, rej) => {
      // here the magic happens
      document.execCommand('copy') ? res() : rej()
      textArea.remove()
    })
  }
}
const onClickImg = (index: number) => {
  if (!product.value) return
  ImagePreview({
    images: product.value.imgList,
    startPosition: index
  })
}
const onEdit = () => {
  router.push({
    name: 'add-product',
    params: {
      id: product.value?.id
    }
  })
}
const onDelete = () => {
  Dialog.confirm({
    message: '确认删除该产品吗?',
    confirmButtonColor: '#228efc'
  }).then(async () => {
    if (!product.value) return
    await deleteProductById(product.value.id)
    Notify({
      message: '删除成功~',
      type: 'success'
    })
    router.go(-1)
  })
}
const onRemoveCollection = async () => {
  if (!product.value) return
  const res = await removeCollectionByProductId(product.value.id)
  if (!res) return
  isCollection.value = false
  Toast('移除收藏成功~')
}
const onAddCollection = async () => {
  if (!product.value) return
  const res = await addCollection(product.value.id)
  if (!res) return
  isCollection.value = true
  Toast('收藏成功~')
}
const loadProduct = async () => {
  const id = route.params.id as string
  const res = await getProduct(parseInt(id))
  product.value = res.data.product
  actions.value.push({
    name: '手机号: ' + res.data.product.user.phone,
    className: res.data.product.user.phone
  })
  actions.value.push({
    name: '微信号: ' + res.data.product.user.wechat,
    className: res.data.product.user.wechat
  })
  actions.value.push({
    name: 'QQ号: ' + res.data.product.user.qq,
    className: res.data.product.user.qq
  })
}
const loadIsCollection = async () => {
  const token = localStorage.getItem('token')
  if (!token) return
  if (product.value && currentUser.value?.id !== 0) {
    const res = await checkIsCollection(product.value.id)
    isCollection.value = res.data.isCollection
  }
}
onMounted(() => {
  loadProduct().then(() => {
    loadIsCollection().then(() => {
      skeletonLoading.value = false
    })
  })
})
</script>

<style lang="scss" scoped>
.product {
  height: 100%;
  background-color: #fff;
  padding: 0 15px;
  .main {
    .detail {
      padding-bottom: 70px;
      .price {
        display: flex;
        align-items: baseline;
        .new {
          color: #ff4142;
          margin-right: 6px;
          strong {
            font-size: 20px;
          }
        }
        .old {
          color: #ccc;
        }
      }
      .desc {
        margin: 20px 0;
        font-size: 16px;
        white-space: break-spaces;
      }
    }
  }
}
</style>
